﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SCADA;
using SCADA.Comm;
using SCADA.Drive;
using SIE.SCADA.Common;
using SIE.SCADA.Common.Log;
using SIE.SCADA.DataHelper.Utilities;
using SIE.SCADA.IOCore.Device;
using SIE.SCADA.WebApi;
using BaseDevice = SIE.SCADA.IOCore.Device.BaseDevice;

namespace SIE.SCADA.ZemtDemo.Machines
{
    class SMDCMachine : BaseProtocol
    {
        public IProject _project = ServerHostManager.GetServerHost().Project;
        public string ApiAddr { get; set; } = "127.0.0.1";
        string deviceName;
        WebApiConfig webApiConfig;
        WebApiClient webApiClient;
        public SMDCMachine(IComm comm, string addr) : base(null, 0)
        {
            deviceName = addr;
            ApiInit();
        }

        /// <summary>
        /// api初始化
        /// </summary>
        private void ApiInit()
        {
            webApiConfig = new WebApiConfig()
            {
                IP = ApiAddr,
                Port = 7666,
                DataFormatter = DataFormatter.Json
            };
            webApiClient = new WebApiClient(webApiConfig);
            webApiClient.Start();
        }

        public override Dictionary<string, RegInfo> ReadNReg(string regNameRange)
        {
            return null;
        }

        public override ExecuteResult<bool> WriteReg(string regName, params int[] @params)
        {
            try
            {
                var valueItem = new ValueItem() { Key = regName, Value = @params.First() };
                return webApiClient.Command.Write(valueItem);
            }
            catch (Exception ex)
            {
                Logger.Error($"{deviceName} {ex.ToString()}");
            }
            return false;
        }

        public bool WriteMessage(string regName, params object[] @params)
        {
            return WriteFullName($"Tag.{deviceName}.{regName}", @params);
        }

        public bool WriteFullName(string regName, params object[] @params)
        {
            try
            {
                var valueItem = new ValueItem() { Key = regName, Value = @params.First() };
                return webApiClient.Command.Write(valueItem);
            }
            catch (Exception ex)
            {
                Logger.Error($"{deviceName} {ex.ToString()}"); 
            }
            return false;
        }

        public ValueItem ReadTag(string tagName)
        {
            try
            {
               var valueItem = webApiClient.Command.Read(tagName);
               return valueItem;
            }
            catch (Exception ex)
            {
                Logger.Error($"{tagName} {ex.ToString()}");
                return null;
            }
        }

        public override void BeginListen(List<string> regNames, int pollTime = 500)
        {
            new System.Threading.Thread(() =>
            {
                isBeginScan = true;
                foreach (var item in regNames)
                {
                    AddListenReg(item, new RegInfo() { Protocol = this, RegName = item });
                }
                var tags = regNames.Where(m=>!string.IsNullOrEmpty(m)).ToDictionary(t => $"IO.{deviceName}.{t}", t => t);
                while (isBeginScan)
                {
                    try
                    {
                        foreach (var item in tags)
                        {
                            var valueItem = ReadTag(item.Key);
                            ListenReg[tags[item.Key]].Value = webApiClient.Command.Read(item.Key)?.Value.ObjToInt();
                        }
                    }
                    catch (Exception ex)
                    {

                        Logger.Warn(ex.Message);
                        Logger.Warn(ex.StackTrace);
                    }
                    //Common.Log.Logger.Trace($"{deviceName} 扫描完成");
                    if (!string.IsNullOrEmpty(HeartHeatRegName))
                    {
                        //Common.Log.Logger.Trace($"{deviceName} 发送心跳");
                        WriteReg(HeartHeatRegName, 0x01);
                    }
                    System.Threading.Thread.Sleep(pollTime);
                }
            }).Start();
        }

        protected override global::SCADA.Drive.BaseMessage SendCmd(BaseCmd cmd)
        {
            return null;
        }


        public override Dictionary<string, RegInfo> ReadNReg(string regName, int length = 1)
        {
            throw new NotImplementedException();
        }
    }
}
